/* $Id: file.c 62 2007-05-24 06:10:38Z aldleonm $
 */
#include "file.h"
#include "extern.h"


/* @brief read file into memory */
/* @param filedescriptor, #define BSZ */
/* @return content of file */
void *
ed_readf(FILE * fd)
{
	char r[BSZ];
	void *inhere = NULL;
	void *temp = NULL;
	int i = 0;
	size_t c = 0;
	struct stat fst;
	off_t fsize;

	if ((fstat(fileno(fd), &fst)) != 0) {
		fprintf(stderr, "error stating the file\n");
		fprintf(stderr, "%s\n", strerror(errno));
		exit(1);
	}
	fsize = fst.st_size;
	while (((i = fread(r, 1, BSZ, fd)) > 0) && ((c <= fsize))) {
		temp = realloc(inhere, c + i);

		if (temp != NULL) {
			memset(temp,0,c+i);
			inhere = temp;
		} else {
			fprintf(stderr, "error reading file into memory\n");
			exit(1);
		}
		memmove((inhere+c), r, i);
		c = c + i;
	}
	return inhere;
}

/* @brief read from stdin
 * @param read size, #define BSZ
 * @return pointer to was red
 */
void *
ed_readstdin(size_t * r_sz)
{
	void *bf = NULL;
	size_t c, i;
	void *temp = NULL;
	size_t bfsz = BSZ; /* buffer size */

	if (!(bf = malloc(bfsz))) {
		exit(1);
	}

	memset(bf, 0, bfsz);
	i = 0;
	c = 0;

	while ((c = read(fileno(stdin), (bf+i), bfsz)) > 1) {
		if (c < bfsz) {
			bfsz = c;
			i = i + c;
			continue;
		}

		bfsz = BSZ;

		if ((temp = realloc(bf, i + c)) == NULL) {
			fprintf(stderr, "_my_readstdin(): realloc() error: %s\n", errno);
			exit(-1);
		}
		bf = memset(temp,0,i+c);
		i = i + c;
	}

	if ((bf != NULL) || i > 1) {
		*r_sz = i;
		return bf;
	}

	/* NOT REACHED */
	return;
}

/*
 * vim: ts=4
 */

/* END */
